﻿/**
 * 定义命名空间
 */
Ext.namespace("Mis.Ext");
/*
*CRUD面板基类
*/
Mis.Ext.CrudPanel=Ext.extend(Ext.Panel,{
	closable: true,
  	autoScroll:true,
  	layout:"fit",
  	gridViewConfig:{},  
	//链接
  	linkRenderer:function(v)
  	{
  		if(!v)return "";
  		else return String.format("<a href='{0}' target='_blank'>{0}</a>",v);
  	},
	//时间
	dateRender:function(format)
    {
    	format=format||"Y-m-d h:i";
    	return Ext.util.Format.dateRenderer(format);
    },
	//查询
    search:function()
    {   
        var sname = this.name.getValue();//得到输入框的值
        //alert(sname);
    	this.store.load({params:{start:0,limit:10,name:sname}});
    },
	//刷新
    refresh:function()
    {
    	this.store.removeAll();
   		this.store.reload();
    },  
	//初始化窗口（用于新增，修改时）,继承后在createWin中调用该方法显示窗口
    initWin:function(width,height,title)
    {
    	var win=new Ext.Window({
			width:width,
			height:height,
			buttonAlign:"center",
			title:title,
			modal:true,
			shadow:true,
			closeAction:"hide",
			items:[this.fp],
			buttons:[{text:"保存",
					  handler:this.save,
					  scope:this},
					  {text:"清空",
					   handler:this.reset,
					   scope:this},
					  {text:"关闭",
					   handler:this.closeWin,
					   scope:this}
					   	]					  
		});
		return win;
    },
	//显示（新增/修改）窗口
    showWin:function()
	{	//createForm()需要在继承时提供，该方法作用是创建表单
		if(!this.win){
			if(!this.fp){
				this.fp=this.createForm();
			}
		this.win=this.createWin();
		this.win.on("close",function(){this.win=null;this.fp=null;this.store.reload();},this);
		}
		//窗口关闭时，数据重新加载
		this.win.show();
	},
	//创建（新增/修改）窗口
	create:function()
	{
		this.showWin();
		this.reset();
	},
	//数据保存[（新增/修改）窗口]
	save:function()
	{
		var id=this.fp.form.findField("Id").getValue();		
		this.fp.form.submit({
				waitMsg:'正在保存。。。',
	            url:this.baseUrl+"?cmd="+(id?"Update":"Save"),
	            method:'POST',
	            success:function(form_instance_create, action){
				Ext.MessageBox.alert('友情提示', action.result.info);
	           	this.closeWin();
	           	this.store.reload();          	
	            },
				failure:function(form_instance_create, action){
				Ext.MessageBox.alert('友情提示', action.result.info);  	
	            },
	            scope:this
		});	
	},
	//（新增/修改）窗口上的清空
	reset:function()
	{
	if(this.win)this.fp.form.reset();
	},
	//（新增/修改）窗口上的关闭
	closeWin:function()
	{
		if(this.win)this.win.close();
		this.win=null;
		this.fp=null;
		this.store.reload();       
	},
	//修改，双击行，或选中一行点击修改，
	edit:function()
	{
		if(this.grid.selModel.hasSelection()){   
				var records = this.grid.selModel.getSelections();//得到被选择的行的数组
				var recordsLen = records.length;//得到行数组的长度
				if( recordsLen>1){
				Ext.Msg.alert("系统提示信息","请选择其中一项进行编辑！");}//一次只给编辑一行
				else{
                        var record=this.grid.getSelectionModel().getSelected();//获取选择的记录集
	                    var id=record.get("id");
	                    this.showWin();
	                    this.fp.form.loadRecord(record); //往表单（fp.form）加载数据
	                }
			    } else {   
                 Ext.Msg.alert("提示","请先选择要编辑的行!");
                }
	},	
	//删除,pid为主键值
	remove:function(pid)
	{
	          //var result;
	          var store=this.store;
	          var baseUrl=this.baseUrl;
              if(this.grid.selModel.hasSelection()){   
						var records = this.grid.selModel.getSelections();//得到被选择的行的数组
						var recordsLen = records.length;//得到行数组的长度
						var jsonStr = '{';
						for(var i=0;i<recordsLen;i++){
							var id = records[i].get(pid);
							if(i!=0){
								jsonStr +=',"'+id+'":'+id ;
							}else{
								jsonStr += '"'+id+'":'+id ;
							}
						}
						jsonStr += '}' ; 
						//this.store.reload();这里能执行
						Ext.MessageBox.confirm('系统提示信息', '确定要删除所选的记录吗?', function(buttonobj){
					if(buttonobj=='yes'){
						var myCon = new Ext.data.Connection();
						Ext.MessageBox.wait('正在删除数据中, 请稍候……'); //出现一个等待条
						myCon.request({
							url:baseUrl+'?cmd=Remove',
							//url:'Plant.aspx?cmd=Remove',
							method:"GET",
							params:{'json':jsonStr},
							//callback : Function (Optional) options, success : Boolean ,response : Object 
							callback:function(a,b,c){
								Ext.MessageBox.hide();
								if(b==true){
									   Ext.Msg.alert("提示信息",c.responseText,function(){store.reload();},this);
								}else{
									    Ext.MessageBox.alert("系统提示信息","异步通讯失败,更新失败,请与管理员联系！");
								}
							}
						},this);
						}//if..yes
					},this);
			    } else {   
                         Ext.Msg.alert("提示","请先选择要删除的行!");
                }
	},
	sm:function()
	{
	      var csm= new Ext.grid.CheckboxSelectionModel();
	      return csm;
	},
	//初始化GRID面板
    initComponent : function(){  
       this.name=new Ext.form.TextField({
					name: 'name',
					anchor:'95%',
					maxLength:25
					}); 
       this.store=new Ext.data.JsonStore({
		id:"Id",
       	url: this.baseUrl+'?cmd=List',//默认的数据源地址，继承时需要提供
       	root: "rows",
  		totalProperty:"totalCount",
  		remoteSort:true,  		
  		fields:this.storeMapping});
      	this.cm.defaultSortable=true;   
      	this.sm= new Ext.grid.CheckboxSelectionModel();	  	
        Mis.Ext.CrudPanel.superclass.initComponent.call(this);
        var viewConfig=Ext.apply({forceFit:true},this.gridViewConfig);  
        this.grid=new Ext.grid.GridPanel({
        store: this.store,
        cm: this.cm,
        sm:this.sm,
        trackMouseOver:false,    
        loadMask: true,
        viewConfig:viewConfig,
        tbar: [{
						id:'addButton',
						text: '新增',
						iconCls:'addIconCss',
						tooltip:'添加新纪录',
						handler: this.create,
                        scope:this
					},'-',//'-'给工具栏按钮之间添加'|'
					{
						id:'editButton',
						text:'编辑',
						iconCls:'editIconCss',
						tooltip:'修改记录',
						handler: this.edit,
                        scope:this
					},'-',
					{
						text:'删除',
						iconCls:'deleteIconCss',
						tooltip:'删除所选中的信息',          
                        handler: this.removeData,
                        scope:this
					},'-',
					{
						text:'刷新',
						iconCls:'refreshIcon',
						tooltip:'刷新纪录',          
                        handler: this.refresh,
                       scope:this
					},'->',//'->'代表让工具栏按钮到右边去
            '用户名: ',this.name,
			{    
                text: '查询',   
                pressed: true,  
                iconCls:'selectIconCss',         
                handler: this.search,
                scope:this
            },'   '
        ],
        bbar: new Ext.PagingToolbar({
            pageSize: 10,
            store: this.store,
            displayInfo: true,
            displayMsg: '显示第 {0} - {1} 条记录，共 {2}条记录',
            emptyMsg: "没有记录"
        })
   		});   
		//双击时执行修改
   		this.grid.on("celldblclick",this.edit,this);       
   		this.add(this.grid);
   		this.store.load({params:{start:0,limit:10}});
        }
});
//用户管理
UserPanel=Ext.extend(Mis.Ext.CrudPanel,{
	//id，需唯一
	id:"userPanel",
	//标题
	title:"用户管理",
	//数据源
	baseUrl:"user.php",
	//表单
	createForm:function(){
	var formPanel=new Ext.form.FormPanel({
		frame:true,
		labelWidth:70,
		labelAlign:'right',
		items:[{
			xtype:'fieldset',
			title:'基本信息',
			autoHeight:true,
			items:[{
				layout:'column',
                border:false,
                defaults:{border:false},
                items:[{
                    	columnWidth:.5,
                        layout:'form',
                        defaultType:'textfield',
                        defaults:{width:120},
                        items:[{xtype:"hidden",name:"Id"},
						{fieldLabel:'用户名',name:'Name',width:120}
						]},{
                    	columnWidth:.5,
                        layout:'form',
                        defaultType:'textfield',
                        defaults:{width:104},
                        items:[{
                        	inputType:'password',
                        	fieldLabel:'密&nbsp;&nbsp;码',
                        	name:'Password'
                        }]
                    }]
			},{
				layout:'form',
	            defaultType:'textfield',
				items:[{
	                	width:300,
	                 	name:"Email",
	                 	fieldLabel:'电子邮箱'
	      	  	}]
		}]
		},{
			xtype:'fieldset',
			title:'备注信息',
			autoHeight:true,
			items:[{
                	xtype:"textarea",
                	width:380,
                	height:80,
                 	name:"Remark",
                 	hideLabel:true
      	  	}]
		}]
	});	
	return formPanel;
    },
	//创建窗口
    createWin:function()
    {
    	return this.initWin(438,300,"用户管理");
    },
	//删除
	removeData:function(){
	//alert(this.baseUrl);
    this.remove('Id');
    } ,
    storeMapping:["Id","Name","Password","Email","Remark"],
    initComponent : function(){   
	var sm = new Ext.grid.CheckboxSelectionModel();
    this.cm=new Ext.grid.ColumnModel([
	new Ext.grid.RowNumberer(),//获得行号
    sm,
    {header: "编号", sortable:true,width: 100, dataIndex:"Id"},
	{header: "用户名", sortable:true,width: 300, dataIndex:"Name"},
	{header: "密码", sortable:true,width: 300, dataIndex:"Password"},
	{header: "电子邮箱", sortable:true,width: 300, dataIndex:"Email"},
	{header: "备注", sortable:true,width: 300, dataIndex:"Remark"}
        ]);
    UserPanel.superclass.initComponent.call(this);   //调用基类的方法
    }
	});
//主panel
MainPanel = function() {
	this.openTab = function(panel, id) {
		var o = (typeof panel == "string" ? panel : id || panel.id);
		var tab = this.getComponent(o);		
		if (tab) {
			this.setActiveTab(tab);
		} else if(typeof panel!="string"){
			panel.id = o;
			var p = this.add(panel);
			this.setActiveTab(p);
		}
	};
	this.closeTab = function(panel, id) {
		var o = (typeof panel == "string" ? panel : id || panel.id);
		var tab = this.getComponent(o);
		if (tab) {
			this.remove(tab);
		}
	};
	MainPanel.superclass.constructor.call(this, {
		id : 'main',
		region : 'center',
		margins : '0 5 5 0',
		resizeTabs : true,
		minTabWidth : 135,
		tabWidth : 135,
		enableTabScroll : true,
		activeTab : 0,
		items : {
			id : 'homePage',
			title : '主页',
			closable : false,
			autoLoad : {
				url : 'about.php'
			},
			autoScroll : true
		}
	});
};
Ext.extend(MainPanel, Ext.TabPanel);